﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using Crossroad.Core.Exceptions;
using Crossroad.Core.Models;
using Crossroad.Utils.Extensions;
using Crossroad.Utils.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace Crossroad.Core.Helper
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            var res = new ResData
            {
                code = HttpStatusCode.Forbidden.Val(),
                message = "服务器拒绝无法完成请求",
            };

            res.message = ex.Message;
            HttpStatusCode statusCode;
            switch (ex)
            {
                case AuthorizeException exception:
                    //无权限异常
                    res.code = exception.HttpCode;
                    statusCode = HttpStatusCode.Unauthorized;
                    break;
                case LogicException exception:
                    //逻辑处理异常
                    res.code = exception.HttpCode;
                    statusCode = HttpStatusCode.Forbidden;
                    break;
                default:
                    //服务器异常
                    res.code = 500;
                    statusCode = HttpStatusCode.InternalServerError;
                    break;
            }

            context.HttpContext.Response.StatusCode = (int) statusCode;
            context.Result = new JsonResult(res);
            //context.Result = new JsonResult(res, new JsonSerializerSettings
            //{
            //    ContractResolver = new UnderlineSplitContractResolver()
            //});

        }


    }
}
